package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;


    @Scheduled(cron = "0 0/1 * * * ?") // 每分钟执行一次
    public void processOrder() {
        // process order logic here
        log.info("定时处理超时订单：{}", LocalDateTime.now());

        // 查询超时订单
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15); // 15 分钟内未支付的订单
        Orders orders = new Orders();
        orders.setPayStatus(Orders.UN_PAID);
        orders.setOrderTime(time);
        List<Orders> list = orderMapper.list(orders); // 查询超时订单

        // 处理超时订单
        if (list != null && list.size() > 0) {
            for (Orders order : list) {
                log.info("处理订单：{}", order.getId());
                order.setStatus(Orders.CANCELLED); // 取消订单
                order.setCancelReason("超时未支付"); // 取消原因
                order.setCancelTime(LocalDateTime.now()); // 取消时间
                orderMapper.update(order); // 更新订单状态
            }

        }
    }

    //处理派送中的订单
    //没凌晨1点钟执行一次
    @Scheduled(cron = "0 0 1 * * ?") // 每天1点钟执行一次
    public void deliveryOrder() {
        log.info("处理派送中的订单");
        // 查询派送中的订单
        Orders orders = new Orders();
        orders.setDeliveryStatus(Orders.DELIVERY_IN_PROGRESS);
        orders.setOrderTime(LocalDateTime.now().plusHours(-1)); // 查询1小时前的订单
        List<Orders> list = orderMapper.list(orders); // 查询派送中的订单

        if (list != null && list.size() > 0) {
            for (Orders order : list) {
                log.info("处理订单：{}", order.getId());
                // 处理订单
                order.setDeliveryStatus(Orders.COMPLETED); // 订单完成
                order.setDeliveryTime(LocalDateTime.now()); // 订单完成时间
                orderMapper.update(order); // 更新订单状态
            }
        }
    }
}
